package com.jiufengxinxi.ts.common.utils.thread;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.*;

public class BaseExecutorService {
	private Logger logger= LoggerFactory.getLogger(this.getClass());

	//private ExecutorService executorService=Executors.newCachedThreadPool();
	
	private ThreadPoolTaskExecutor poolTaskExecutor=null;
	
	public void execute(BaseThreadRunnable threadRunnable){
		if(poolTaskExecutor==null){
//			poolTaskExecutor=new ThreadPoolTaskExecutor();
//			poolTaskExecutor.setCorePoolSize(6);
//			poolTaskExecutor.setKeepAliveSeconds(200);
//			poolTaskExecutor.setMaxPoolSize(10);
//			poolTaskExecutor.setQueueCapacity(300);
//			poolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
//			poolTaskExecutor.initialize();
			init();
		}

		poolTaskExecutor.execute(threadRunnable);
	}

	public <T> T submit(Callable<T> call,long times) throws TimeoutException, InterruptedException, ExecutionException{
		if(poolTaskExecutor==null){
			init();
		}
		T result=null;
		Future<T> future = poolTaskExecutor.submit(call);
		result=future.get(times, TimeUnit.MILLISECONDS);
		return result;
	}


	public <T> T submit(Callable<T> call) throws TimeoutException, InterruptedException, ExecutionException{
		return submit(call,10*1000);
	}

	private void init(){
		logger.info("开始初始化线程");
//		poolTaskExecutor=new ThreadPoolTaskExecutor();
//		poolTaskExecutor.setCorePoolSize(30);
//		poolTaskExecutor.setMaxPoolSize(1024);
//		poolTaskExecutor.setQueueCapacity(10000);
//		poolTaskExecutor.setKeepAliveSeconds(1000);
//		poolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
//		poolTaskExecutor.initialize();



		try{
//			poolTaskExecutor=ServicesFactory.getBean("poolTaskExecutor");//poolTaskExecutor
		}catch(Exception e){
			logger.error("初始化线程失败");
			/*poolTaskExecutor=new ThreadPoolTaskExecutor();
			poolTaskExecutor.setCorePoolSize(30);
			poolTaskExecutor.setMaxPoolSize(1024);
			poolTaskExecutor.setQueueCapacity(10000);
			poolTaskExecutor.setKeepAliveSeconds(1000);
			poolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
			poolTaskExecutor.initialize();*/
		}

		try{
			if(poolTaskExecutor==null){
				init();
			}
		}catch(Exception e){
			logger.error("初始化线程失败");
		}
	}

	public ThreadPoolTaskExecutor getPoolTaskExecutor() {
		return poolTaskExecutor;
	}

	public void setPoolTaskExecutor(ThreadPoolTaskExecutor poolTaskExecutor) {
		this.poolTaskExecutor = poolTaskExecutor;
	}
	
}
